<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Games;
use App\Models\Orders;
use App\Services\WanSdk\WanSdkService;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index(Request $request)
    {
        $order = Orders::find(34);
        $game = Games::where('game_id', $order->game_id)->first();
        return view('h5sdk.pay', [
            'order'        => $order,
            'pay_platform' => Orders::PAY_PLATFORM_WAN_WECHAT_JSSDK,
            'game'         => $game,
            'game_url'     => WanSdkService::getInstance()->getGameUrl($order->game_id, $order->game_channel_id),
        ]);
    }

    public function adpage(Request $request, $page_id)
    {
        return view("test.adpage_{$page_id}");
    }

    public function sign(Request $request)
    {
        if (!$request->isMethod('post')) {
            return view('sign/demo', []);
        }

        $appkey     = trim($request->input('appkey'));
        $params_str = urldecode(trim($request->input('content')));
        if (empty($appkey) || empty($params_str)) {
            return yqerr(10000);
        }

        $arr    = explode('&', $params_str);
        $params = [];
        foreach ($arr as $item) {
            $arr2 = explode('=', $item);
            if (empty($arr2) || count($arr2) != 2) {
                continue;
            }
            $params[$arr2[0]] = $arr2[1];
        }

        $arr = [];
        ksort($params);
        foreach ($params as $key => $val) {
            if ($key === 'sign') continue;
            if ($val === '' || $val === 'null' || is_null($val)) continue;
            $arr[] = "$key=$val";
        }
        $str  = implode("&", $arr) . "$appkey";
        $lstr = strtolower($str);
        $sign = md5($lstr);
        return yqok([
            'appkey'     => $appkey,
            'params_str' => $params_str,
            'str'        => $str,
            'lstr'       => $lstr,
            'sign'       => $sign,
        ]);
    }
}
